import { _decorator } from 'cc';
import { on_network_exception } from '../A-FRAME/network/HttpService';
import { GameData } from '../Data/GameData';
import { UserData } from '../Data/UserData';
import { LocalStorageMgr } from '../Mgr/LocalStorageMgr';
import { NCPoint } from '../src/api/api.config.client';
import { ClientAPI } from '../src/api/client.api';
import ServiceAPI from '../src/api/service.api';
import I18n, { CountryType, LangType } from '../Tools/i18n/I18n';
const { ccclass, property } = _decorator;

const COUNTRY_LIST = ['US', "GB", "CA", "AU"];

const DEFAULT_LOCAL = {
    countryCode: 'US',
    languageCode: 'en'
}

export default class InitData {
    private static load_user_data_np: mtec.NudityPromise<boolean>;

    /** 用户数据是否加载完成 */
    public static get userDataLoaded() {
        return Promise.resolve(InitData.load_user_data_np?.promise ?? false);
    }

    public static init() {
        ServiceAPI.onException(async () => {
            let network = await ClientAPI.Network();
            return [network, 1];
        });
        on_network_exception((reqID, retryTime, delayMS, statusCode) => {
            ClientAPI.Point(NCPoint.NETWORK_EXCEPTION, {
                userid: UserData?.data?.userId ?? -99,
                reqID, retryTime, delayMS, statusCode, isUpOur: 0
            });
        });

        this.loadUserData();//Test模式下注释掉

        this.getWithdrawConf().then(conf => GameData.data.withdrawConfig = conf);
    }

    private static async initUserInfo() {
        console.log("初始化用户");
        let [local, device_id] = await Promise.all([ClientAPI.Local(), ClientAPI.DeviceID().then(res => res.device_id)]);
        UserData.data.deviceId = device_id;
        if (!COUNTRY_LIST.includes(local.countryCode)) {
            local = DEFAULT_LOCAL;
        }
        let initUser = await ServiceAPI.initUser(device_id, local.countryCode);
        if (!initUser) {
            initUser = {
                userId: -99,
                country: DEFAULT_LOCAL.countryCode,
                language: DEFAULT_LOCAL.languageCode,
            };
        };
        console.log(initUser);
        UserData.data.userId = initUser.userId;
        UserData.data.country = initUser.country;
        UserData.data.language = initUser.language;
    }

    public static async loadUserData() {
        console.log('用户id:', UserData.data.userId, '是否是新手:', UserData.data.isCommer);
        if (InitData.load_user_data_np) {
            InitData.load_user_data_np.resolve(!(UserData.data?.userId < 0));
        }
        InitData.load_user_data_np = new mtec.NudityPromise();

        //  初始化用户
        // if (UserData.data.userId == null || UserData.data.isCommer != false) {
        //     LocalStorageMgr.clear();
        //     await this.initUserInfo();
        // }
        console.log(UserData.data.userId, UserData.data.userId != -99, !UserData.data.isCommer);

        if (UserData.data.userId && UserData.data.userId != -99 && !UserData.data.isCommer) {
            // 正常过了新手引导的用户
        } else {
            // 其他所有
            LocalStorageMgr.clear();
            await this.initUserInfo();
        }

        let userInfo: Awaited<ReturnType<typeof ServiceAPI.userInfo>>;
        if (UserData.data.userId >= 0) {
            userInfo = await ServiceAPI.userInfo(UserData.data.userId);
        }

        if (!userInfo) {
            userInfo = {
                country: DEFAULT_LOCAL.countryCode,
                language: DEFAULT_LOCAL.languageCode,
                cashTotal: UserData.data.curCashTotal ?? 0,
                redPacket: UserData.data.redPacket ?? 0
            };
        };

        console.log('user info', userInfo);
        // 获取地区配置
        GameData.data.confCountry = await ServiceAPI.ConfCountry(userInfo.country);
        UserData.data.country = GameData.data?.confCountry?.country ?? userInfo.country;
        UserData.data.language = GameData.data?.confCountry?.language ?? userInfo.language;

        I18n.init(UserData.data.language as LangType, UserData.data.country as CountryType);


        // 更新钱数
        UserData.data.curCashTotal = userInfo.cashTotal;
        // 更新红包数
        UserData.data.redPacket = userInfo.redPacket;

        if (UserData.data.userId >= 0) {
            let ConfCommon = await ServiceAPI.ConfCommon(UserData.data.userId);
            UserData.data.passLevelTimes = ConfCommon?.eliminateTotal;
            UserData.data.drawTotal = ConfCommon?.drawTotal;
            GameData.data.forceConfig = ConfCommon?.forceConfig;
            GameData.data.drawProcessConfig = ConfCommon?.drawProcessConfig;
        }

        /// 初始化默认值
        if (UserData.data.isCommer == null) {
            UserData.data.guideRecord = 1;
        }
        
        if (typeof Default_UserData == 'object' && Default_UserData !== null) {
            Reflect.ownKeys(Default_UserData).forEach(key => {
                // console.log(key, [undefined, null].includes(Reflect.get(UserData.data, key)));

                if ([undefined, null].includes(Reflect.get(UserData.data, key))) {
                    Reflect.set(UserData.data, key, Reflect.get(Default_UserData, key));
                }
            });
        }
        
        InitData.load_user_data_np.resolve(UserData.data.userId >= 0);
    }

    /** 检查用户信息，并在异常时默认加载一次, 但只能在下一次获得更新的用户信息 */
    public static async checkUserInfo() {
        let loaded = await InitData.userDataLoaded;
        console.log(loaded);
        if (loaded) {

        } else {
            console.log('重新加载用户');

            InitData.loadUserData();
        }

        return loaded;
    }

    private static withdraw_config: ReturnType<typeof ServiceAPI.WithdrawConfig>;
    public static async getWithdrawConf(update: boolean = false) {
        if (!InitData.withdraw_config || update) {
            if (await InitData.userDataLoaded) {

            } else {
                await InitData.loadUserData();
            }

            if (UserData.data.userId >= 0) {
                this.withdraw_config = ServiceAPI.WithdrawConfig(UserData.data.userId);
            }
        }

        return Promise.resolve(InitData.withdraw_config);
    }
}

const Default_UserData = {
    //  全凭强弹次数
    fullscTimes: 0,
    //  是否初始化关卡数
    curLevel: 0,
    //  是否初始化道具个数
    propNum: 1,
    //  是否初始化新手
    isCommer: true,
    //  是否初始化抽奖次数
    curlotteryTimes: 0,
    //  达成抽奖条件次数
    curGetLotteryTimes: 1,
    //  是否初始化抽奖机会数
    curlotteryChance: 0,
    //  是否初始化 过关次数-临时，用于lottery弹版
    tempPassLevelTimes_lottery: 0,
    //  是否初始化 过关次数-临时，用于强弹
    tempElimiTimes_lucky: 0,
    //是否初始化 普通领取红包的次数
    luckyWardNorgetTimes: 0,
}

